package cn.itsource.ymcc.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.itsource.ymcc.constant.CacheConstants;
import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.errorcode.ErrorCode;
import cn.itsource.ymcc.exception.GlobalException;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.ICommonService;
import cn.itsource.ymcc.util.AssertUtil;
import cn.itsource.ymcc.util.StrUtils;
import cn.itsource.ymcc.vo.PhoneCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class CommonServiceImpl implements ICommonService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public JsonResult getImageCode(String key) {
        AssertUtil.isNotNull(key, "请求参数不正确");
        //图形验证码 糊涂工具包
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(300, 100, RConst.Num.INT_4, RConst.Num.INT_4);
        String imageCode = captcha.getCode();

        //保存至redis
        redisTemplate.opsForValue().set(key, imageCode, Duration.ofMinutes(RConst.Num.INT_3));

        //base64编码
        String imageBase64 = captcha.getImageBase64();

        return JsonResult.success().setData(imageBase64);
    }

    /**
     *
     * @param phoneCodeVo
     * @return
     */
    @Override
    public JsonResult SendSmsCode(PhoneCodeVo phoneCodeVo) {
        AssertUtil.isNotNull(phoneCodeVo.getImageCode(), ErrorCode.IMG_CODE_IS_EMPTY.getMessage());
        Boolean aBoolean = redisTemplate.hasKey(phoneCodeVo.getUuid());
        AssertUtil.isTrue(aBoolean, ErrorCode.IMG_CODE_EXPIRED.getMessage());

        String imgcode = redisTemplate.opsForValue().get(phoneCodeVo.getUuid()).toString();
        AssertUtil.isTrue(phoneCodeVo.getImageCode().equalsIgnoreCase(imgcode), ErrorCode.IMG_CODE_INPUT_ERROR.getMessage());

        //生成一个6位数验证码
        String phoneCode = StrUtils.getComplexRandomString(RConst.Num.INT_6);
        //判断redis里面是否有验证码
        Boolean flag = redisTemplate.hasKey(CacheConstants.PHONE_CODE_KEY + phoneCodeVo.getMobile());
        if (flag) {
            Long expire = redisTemplate.getExpire(CacheConstants.PHONE_CODE_KEY + phoneCodeVo.getMobile());
            if (expire > RConst.Num.LONG_240){
                throw new GlobalException(ErrorCode.NOT_KEEP_CLICKING);
            }
            phoneCode = redisTemplate.opsForValue().get(CacheConstants.PHONE_CODE_KEY + phoneCodeVo.getMobile()).toString();
        }
        System.out.println(phoneCode);
        //手机号验证码缓存到redis
        redisTemplate.opsForValue().set(CacheConstants.PHONE_CODE_KEY + phoneCodeVo.getMobile(), phoneCode, Duration.ofMinutes(RConst.Num.INT_5));


        return JsonResult.success();
    }
}
